package com.work.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Author: 星川
 * @Date: 2023/05/12/10:56
 * @Description:
 */
public class RedisUtils {
    //每天最大次数
    public static final int MAX_PER_DAY = 10;

    public static final String CACHE_PRODUCT_ID = "cache:product:id:";

    //60秒
    public static final int INTERVAL = 60;

    //验证码失效时间
    public static final int EXPIRATION = 300;

    //每天发送的次数的key
    public static final String SEND_COUNT_KEY = "sms:count:" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ":";
    //最后发送的时间的key
    public static final String LAST_SEND_TIME_KEY = "sms:last_send_time:";

    //验证码的key
    public static final String CAPTCHA_KEY = "sms:captcha:";

    public static final String CACHE_PRODUCT_PAGE = "cache:product:page:";

    public static final String CACHE_IMAGE_LIST = "cache:image:list:";

    /**
     * 校验是否超过每天发送的最大次数
     *
     * @param phone
     * @param redisTemplate
     * @return
     */
    public static boolean checkMaxPerDay(String phone, StringRedisTemplate redisTemplate) {
        //"sms:count:2023-05-12:138383838"
        String sendCount = redisTemplate.opsForValue().get(SEND_COUNT_KEY + phone);//
        if (sendCount == null) {
            return false;
        }
        return Integer.parseInt(sendCount) > MAX_PER_DAY;
    }

    /**
     * 校验发送频率是否过快
     */
    public static boolean checkSendInterval(String phone, StringRedisTemplate redisTemplate) {
        String lastSendTimeStr = redisTemplate.opsForValue().get(LAST_SEND_TIME_KEY + phone);
        if (lastSendTimeStr == null) {
            return false;
        }
        //上次一发送的时间
        long lastSendTime = Long.parseLong(lastSendTimeStr);
        //当前时间
        long now = System.currentTimeMillis();
        //如果当前时间-上一次发送时间 》1分钟
        if (now - lastSendTime >= INTERVAL * 1000L) {
            //更新发送时间为现在
            redisTemplate.opsForValue().set(LAST_SEND_TIME_KEY + phone, String.valueOf(now));
            return false;
        }
        return true;
    }
}
